#include "CircularQueue.h"

MyCircularQueue* myCircularQueueCreate(int k) {
    MyCircularQueue* obj = (MyCircularQueue*)malloc(sizeof(MyCircularQueue));
    if (obj == NULL)
    {
        perror("malloc fail");
        return NULL;
    }
    obj->data = (int*)malloc(sizeof(int) * (k + 1));
    if (obj->data == NULL)
    {
        perror("malloc fail");
        return NULL;
    }
    obj->front = obj->rear = 0;
    obj->k = k;
    return obj;
}

bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {
    if (myCircularQueueIsFull(obj))
        return false;
    obj->data[obj->rear] = value;
    obj->rear = (obj->rear + 1) % (obj->k + 1);
    return true;

}

bool myCircularQueueDeQueue(MyCircularQueue* obj) {
    if (myCircularQueueIsEmpty(obj))
        return false;
    obj->front = (obj->front + 1) % (obj->k + 1);
    return true;

}

int myCircularQueueFront(MyCircularQueue* obj) {
    if (myCircularQueueIsEmpty(obj))
        return -1;
    return obj->data[obj->front];
}

int myCircularQueueRear(MyCircularQueue* obj) {
    if (myCircularQueueIsEmpty(obj))
        return -1;
    if (obj->rear == 0)
    {
        return obj->data[obj->k];
    }
    else
    {
        return obj->data[obj->rear - 1];
    }

    //return obj->data[(obj->rear+obj->k)%(obj->k+1)];
}

bool myCircularQueueIsEmpty(MyCircularQueue* obj) {
    return obj->front == obj->rear;
}

bool myCircularQueueIsFull(MyCircularQueue* obj) {
    return (obj->rear + 1) % (obj->k + 1) == obj->front;
}

void myCircularQueueFree(MyCircularQueue* obj) {
    free(obj->data);
    free(obj);
}
